<template>
  <div class="settings-container">
    <div class="header">
      <div class="back-icon" @click="goBack">
        <i class="icon-back"></i>
      </div>
      <div class="title">设置</div>
    </div>

    <div class="settings-list">
      <div class="setting-item">
        <div class="label">头像</div>
        <div class="value">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:1017/users/getUpdate"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{ Token }"
            :data="{ userId: userInfo.userId, avatar: userInfo.avatar }"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" :style="{objectFit: fitType}" />
            <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
          </el-upload>
        </div>
      </div>
      <div class="setting-item"  @click="showNicknameModal">
        <div class="label">昵称</div>
        <div class="value">
          {{ userInfo.nickname }}
          <i class="icon-arrow-right"></i>
        </div>
      </div>

      <div class="setting-item">
        <div class="label">手机号</div>
        <div class="value">
          {{ formatPhone(userInfo.phone) }}
        </div>
      </div>
      <div class="setting-item" @click="$router.push('/about')">
        <div class="label">关于我们</div>
        <div class="value">
          <i class="icon-info" ></i>
        </div>
      </div>
      <div class="setting-item" @click="$router.push('/feedback')">
        <div class="label">意见反馈</div>
        <div class="value">
          <i class="icon-feedback"></i>
        </div>
      </div>
      <div class="setting-item logout" @click="handleLogout">
        退出登录
      </div>
    </div>

    <!-- 修改昵称弹窗 -->
    <div class="modal" v-if="isNicknameModalVisible">
      <div class="modal-content">
        <div class="modal-title">修改昵称</div>
        <input
          type="text"
          v-model="newNickname"
          class="input"
          placeholder="请输入新昵称"
          maxlength="20"
        />
        <div class="error-message" v-if="errorMessage">{{ errorMessage }}</div>
        <div class="modal-button-container">
          <div class="modal-button cancel" @click="hideNicknameModal">取消</div>
          <div class="modal-button confirm" @click="saveNickname">保存</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 定义响应式数据
const router = useRouter();
const userInfo = ref({
  nickname: '',
  avatar: '',
  phone: '',
  userId: ''
});

const isNicknameModalVisible = ref(false);
const newNickname = ref('');
const errorMessage = ref('');
const showGreeting = ref(false);
const fitType = ref('contain');

// 定义方法
const goBack = () => {
  router.back();
};

const formatPhone = (phone) => {
  if(!phone) return '';
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

const showNicknameModal = () => {
  isNicknameModalVisible.value = true;
  newNickname.value = userInfo.value.nickname;
};

const hideNicknameModal = () => {
  isNicknameModalVisible.value = false;
  newNickname.value = '';
  errorMessage.value = '';
};

let Token = "";

const getToken = () => {
  Token = sessionStorage.getItem("phone") || "";
}

const handleAvatarSuccess = (response) => {
  if (response.status === 200) {
    userInfo.value.avatar = response.data.avatar;
    sessionStorage.setItem('users', JSON.stringify(userInfo.value));
    ElMessage.success('头像修改成功');
  // } else {
  //   ElMessage.error(response.message || '修改失败');
  }
};
const beforeAvatarUpload = (file) => {
  const isValidFormat = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isValidFormat) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }

  if (!Token) {
    ElMessage.error('未登录,请先登录');
    return false;
  }

  return isValidFormat && isLt2M;
};

// 确保在组件挂载时获取 Token
onMounted(() => {
  const route = useRoute();
  // 判断是否从其他页面跳转过来，这里假设从其他页面跳转过来时会带有from参数
  if (route.query.from) {
    showGreeting.value = true;
  }
  getToken(); // 确保在组件挂载时获取 Token
});

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: 'http://localhost:1017',
  withCredentials: false, // 修改为false以避免CORS问题
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
apiClient.interceptors.request.use(
  config => {
    if (Token) {
      config.headers['Token'] = Token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    console.error('请求失败:', error);
    throw error;
  }
);

const saveNickname = () => {
  // 验证昵称是否为空
  if (!newNickname.value.trim()) {
    errorMessage.value = '昵称不能为空';
    return;
  }

  // 确保已获取Token
  if (!Token) {
    errorMessage.value = '未登录,请先登录';
    return;
  }

  // 准备请求数据
  const requestData = {
    userId: userInfo.value.userId,
    nickname: newNickname.value
  };

  // 发送修改昵称请求
  apiClient.post('/users/getWorkUpdate', requestData)
    .then(response => {
      const data = response.data;
      if (data.code === 200) {
        // 更新本地存储的用户信息
        userInfo.value.nickname = newNickname.value;
        sessionStorage.setItem('users', JSON.stringify(userInfo.value));

        // 关闭弹窗
        hideNicknameModal();
      } else {
        errorMessage.value = data.message || '修改成功';
      }
    })
    .catch(error => {
      console.error('修改昵称失败:', error);
      errorMessage.value = '修改失败,请稍后重试';
    });
};

const handleLogout = () => {
  sessionStorage.clear();
  router.push('/login');
};

onMounted(() => {
  const userData = sessionStorage.getItem('users');
  if(userData) {
    userInfo.value = JSON.parse(userData);
  }
});
</script>

<style scoped>
.settings-container {
  background-color: #f5f5f5;
  font-family: Arial, sans-serif;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  background: linear-gradient(to right, #8A2BE2, #008080);
  color: #fff;
  padding: 15px;
}

.back-icon {
  font-size: 24px;
  cursor: pointer;
  margin-right: 10px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.settings-list {
  margin: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.setting-item:hover {
  background-color: #f9f9f9;
}

.label {
  font-size: 16px;
  color: #333;
}

.value {
  display: flex;
  align-items: center;
  color: #666;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 2px solid #eee;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 48px;
  height: 48px;
  line-height: 48px;
  text-align: center;
}

.icon-arrow-right,
.icon-info,
.icon-feedback {
  font-size: 20px;
  color: #999;
  margin-left: 8px;
}

.logout {
  color: #ff4d4f;
  font-weight: 500;
  justify-content: center;
  margin-top: 20px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  padding: 24px;
  border-radius: 16px;
  width: 85%;
  max-width: 420px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.input:focus {
  outline: none;
  border-color: #8A2BE2;
}

.error-message {
  color: #ff4d4f;
  margin-bottom: 16px;
  font-size: 14px;
}

.modal-button-container {
  display: flex;
  justify-content: space-between;
  gap: 12px;
}

.modal-button {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
}

.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.cancel:hover {
  background-color: #eee;
}

.confirm {
  background-color: #8A2BE2;
  color: #fff;
}

.confirm:hover {
  background-color: #7B1FA2;
}

@media (max-width: 480px) {
  .modal-content {
    width: 95%;
    padding: 20px;
  }

  .settings-list {
    margin: 12px;
  }
}
</style>